﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tdb.YY.API.Extensions;
using Tdb.YY.Helper;

namespace Tdb.YY.API.Filters
{
    /// <summary>
    /// 授权过滤器特性
    /// </summary>
    public class AuthFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 验权
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //允许匿名
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            //获取token
            //var token = ((HttpRequestHeaders)context.HttpContext.Request.Headers).HeaderAuthorization.FirstOrDefault();
            var token = ((DefaultHttpRequest)context.HttpContext.Request).Headers["Authorization"].ToString();

            //获取ip
            var ip = context.HttpContext.GetClientIp();

            //JWT验证
            var ret = JWTHelper.CheckToken(token, ip);

            //验证不通过
            if (ret == false)
            {
                LogHelper.Debug($"token验证不通过。token：{token}，ip：{ip}");

                context.Result = new UnauthorizedResult();
                return;
            }
        }
    }
}
